package com.hhdys.service;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang3.math.NumberUtils;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.hhdys.dao.AccountFuncAssMapper;
import com.hhdys.model.Account;
import com.hhdys.model.AccountFuncAss;
import com.hhdys.model.AccountFuncAssExample;
import com.hhdys.model.RoleFuncAss;
import com.hhdys.shiro.DefaultRealm;

@Service
@Transactional
public class AccountFuncServiceImpl implements AccountFuncService {
	@Autowired
	private AccountFuncAssMapper dao;
	@Autowired
	private AccountService accountService;
	@Autowired
	private RoleFuncAssService roleAssService;
	@Autowired
	private DefaultRealm realm;

	@Override
	public Set<Integer> getAssByAccountId(int accountId) {
		AccountFuncAssExample example = new AccountFuncAssExample();
		AccountFuncAssExample.Criteria criteria = example.createCriteria();
		criteria.andAccountIdEqualTo(accountId);
		List<AccountFuncAss> list = dao.selectByExample(example);
		Set<Integer> funs = getFuncByAccountId(accountId);
		for (AccountFuncAss ass : list) {
			funs.add(ass.getFuncId());
		}
		return funs;
	}

	private Set<Integer> getFuncByAccountId(int accountId) {
		Account account = accountService.getAccountById(accountId);
		Set<Integer> set = new HashSet<Integer>();
		List<RoleFuncAss> roleFuncAsses = roleAssService.getAssByRoleId(account
				.getRole());
		for (RoleFuncAss ass : roleFuncAsses) {
			set.add(ass.getFuncId());
		}
		return set;
	}

	@Override
	public boolean addAss(int accountId, String funcs) {
		Set<Integer> set = getFuncByAccountId(accountId);
		String[] strs = funcs.split(",");
		AccountFuncAssExample example = new AccountFuncAssExample();
		AccountFuncAssExample.Criteria criteria = example.createCriteria();
		criteria.andAccountIdEqualTo(accountId);
		dao.deleteByExample(example);// 删除原有的功能

		for (String str : strs) {
			int funcId = NumberUtils.toInt(str);
			if (!set.contains(funcId)) {
				AccountFuncAss ass = new AccountFuncAss();
				ass.setAccountId(accountId);
				ass.setFuncId(funcId);
				dao.insert(ass);
			}
		}
		// 清空权限缓存
		SimplePrincipalCollection principals = new SimplePrincipalCollection();
		Account account = accountService.getAccountById(accountId);
		principals.add(account.getUsername(), realm.getName());
		realm.clearCachedAuthorizationInfo(principals);

		return true;
	}

}
